using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Diagnostics;

namespace SPALM.SharePointSoftwareFactory.SetupHelper.SPSFFiles
{
  public partial class MSIContainer : UserControl
  {
    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    public bool Uninstaller
    {
      get
      {
        return uninstaller;
      }
      set
      {
        uninstaller = value;
        Load();
      }
    }
    private bool uninstaller = false;

    public MSIContainer()
    {
      InitializeComponent();

      Load();
    }

    private bool devEnvChecked = false;
    private void CheckDevenvRunning()
    {
      if (!devEnvChecked)
      {
        if (IsProcessRunning("DEVENV"))
        {
          devEnvChecked = true;
          //MessageBox.Show("Please close all instances of Visual Studio before proceeding with the installation.");
        }
      }
    }

    private bool IsProcessRunning(string name)
    {
      foreach (Process clsProcess in Process.GetProcesses())
      {
        if (clsProcess.ProcessName.ToUpper().Contains(name))
        {
          //if the process is found to be running then we
          //return a true
          return true;
        }
      }
      //otherwise we return a false
      return false;
    }

    public void Load()
    {

      if (uninstaller)
      {
        this.label1.Text = "Please remove the following older components";
      }

      string setupDir = Path.Combine(Path.GetTempPath(), "DownloadSPSF");
      if (!Directory.Exists(setupDir))
      {
        Directory.CreateDirectory(setupDir);
      }

      Stream resourceStream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SPALM.SharePointSoftwareFactory.SetupHelper.SetupFiles.xml");
      if (Uninstaller)
      {
        resourceStream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SPALM.SharePointSoftwareFactory.SetupHelper.UninstallFiles.xml");
      }

      if (resourceStream != null)
      {
        this.LoadControls(setupDir, resourceStream);
      }
    }

    protected override void OnParentChanged(EventArgs e)
    {
      base.OnParentChanged(e);

      if (this.ParentForm != null)
      {
        this.ParentForm.Activated += new EventHandler(ParentForm_Activated);
      }
    }

    private bool parentFormEventAdded = false;
    protected override void OnVisibleChanged(EventArgs e)
    {
      base.OnVisibleChanged(e);

      if (this.ParentForm != null)
      {
        if (!parentFormEventAdded)
        {
          parentFormEventAdded = true;
          this.ParentForm.Activated += new EventHandler(ParentForm_Activated);
        }
      }
    }

    void ParentForm_Activated(object sender, EventArgs e)
    {
      //if form receives focus, e.g. after an installation finishes, we refresh the view of installed applications
      CheckInstallation();
    }

    public void LoadControls(string setupDir, Stream filename)
    {
      panelMain.Controls.Clear();

      XmlDocument doc = new XmlDocument();
      doc.Load(filename);

      foreach (XmlNode node in doc.SelectNodes("/SetupFiles/SetupFile"))
      {
        MSIFile cd = new MSIFile(this, this.Uninstaller, setupDir, GetNodeInnerText(node, "Title"), GetNodeInnerText(node, "Description"), GetNodeInnerText(node, "ProductGuid"), GetNodeInnerText(node, "CheckRegKey"), GetNodeInnerText(node, "SetupFilename"), GetNodeInnerText(node, "VSVersion"), GetNodeInnerText(node, "CheckFileExists"));
        cd.Dock = DockStyle.Top;

        panelMain.Controls.Add(cd);
        cd.BringToFront();
      }

      bool hasElements = false;
      foreach (Control control in panelMain.Controls)
      {
        if (control is MSIFile)
        {
          if ((control as MSIFile).Visible)
          {
            hasElements = true;
          }
        }
      }
      if (!hasElements)
      {
        if (this.Parent is IntermediateStep)
        {
          (this.Parent as IntermediateStep).Enabled = false;
        }
      }
    }

    private string GetNodeInnerText(XmlNode node, string childNodeName)
    {
      try
      {
        return node.SelectSingleNode(childNodeName).InnerText;
      }
      catch { }
      return "";
    }

    private void button1_Click(object sender, EventArgs e)
    {
      CheckInstallation();
    }

    public void CheckInstallation()
    {
      foreach (Control c in panelMain.Controls)
      {
        if (c is MSIFile)
        {
          ((MSIFile)c).CheckInstallation();
        }
      }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
      try
      {
        //lets check each 5 seconds if new software has been installed
        CheckInstallation();
      }
      catch (Exception)
      {
      }
    }

    internal void SetVSVersions(bool vs2008, bool vs2010)
    {
      foreach (Control control in panelMain.Controls)
      {
        if (control is MSIFile)
        {
          (control as MSIFile).SetVSVersions(vs2008, vs2010);
        }
      }
    }

    private void MSIContainer_VisibleChanged(object sender, EventArgs e)
    {
      if (Visible)
      {
        foreach (Control control in panelMain.Controls)
        {
          if (control is MSIFile)
          {
            (control as MSIFile).CheckInstallation();
          }
        }

        CheckDevenvRunning();
      }
    }
  }
}
